import axiosOrigin from 'axios'
import { useMenuStore } from '@/stores/menu'
import router from '@/router'
// 重复引入 会导致一些样式问题如弹出框出现在下面没有css
// import { ElNotification, ElMessage } from 'element-plus'
export const axios = axiosOrigin.create({
  baseURL: import.meta.env.VITE_API_SERVICE || 'http://localhost:9090'
})

axios.interceptors.request.use((config) => {
  const store = useMenuStore()
  if (store.token) {
    config.headers.Authorization = 'Bearer ' + store.token
  }
  return config
})

axios.interceptors.response.use(
  (res) => {
    const store = useMenuStore()
    // console.log(res)
    if (res.status === 288) {
      // console.log('expected exception')
      if (res.data && res.data.code) {
        switch (res.data.code) {
          case 666:
            ElMessage.warning(res.data.msg)
            break
          case 888:
            ElMessage.warning(res.data.msg)
            break
          case 27701:
            ElNotification.success(res.data.msg)
            break
          case 27702:
            store.token = null
            router.push('/login')
            console.log(res.data.msg)
            ElNotification.success('token is expired, please login again')
            break
          default:
            ElMessage.info(res.data.msg)
            break
        }
      }
      return new Promise(() => {})
    } else {
      return res
    }
  },
  (error) => {
    if (error && error.response) {
      switch (error.response.status) {
        case 401:
          ElNotification.success(error.response.data.msg)
          router.push('/login')
          break

        default:
          break
      }
    }
    return new Promise(() => {})
  }
)
